<script setup lang="ts">
import {onMounted, ref,} from 'vue'


const videoA = ref<HTMLVideoElement>() as any
const videoB = ref<HTMLVideoElement>() as any

const getNewStream = async () => {
  let stream = new MediaStream()

  let video_stm = await navigator.mediaDevices.getUserMedia({
    video:true
  })

  let audio_stm = await navigator.mediaDevices.getUserMedia({
    audio:true
  })

  video_stm.getVideoTracks().map(row => stream.addTrack(row))
  audio_stm.getVideoTracks().map(row => stream.addTrack(row))
  
  videoA.value.srcObject  = stream
  
  return stream
}

async function init(){
  let stream = await getNewStream()

  var peerA = new RTCPeerConnection()
  var peerB = new RTCPeerConnection()

  stream.getTracks().forEach(track => {
    peerA.addTrack(track, stream)
  })
  // 这里要注意：必须 peerA 添加媒体数据之后，才能进行下一步! 否则后续环节中 peerB 的 ontrack 事件就不会触发，也就不会拿到媒体流数据。

  peerB.ontrack = async event => {
    let [ remoteStream ] = event.streams
    videoB.value.srcObject = remoteStream
  }
  
  /**
   * 建立连接最重要的角色是 SDP（RTCSessionDescription），翻译过来就是 会话描述。连接双方需要各自建立一个 SDP，但是他们的 SDP 是不同的。发起端的 SDP 被称为 offer，接收端的 SDP 被称为 answer
   * 两端建立对等连接的本质就是互换 SDP，在互换的过程中相互验证，验证成功后两端的连接才能成功
   * 注意：当 peerB.setRemoteDescription 执行之后，peerB.ontrack 事件就会触发。当然前提是第一步为 peerA 添加了媒体数据
   */
  // 注意先后顺序 一步也不能错  A生成offer 后给B 将 offer 设置为远程描述，然后B才能生成answer 将 answer 设置为本地描述  然后A先设置本地描述  再设置远程描述  此过程应该是有一个验证环节
  var offer = await peerA.createOffer()
  await peerB.setRemoteDescription(offer)


  var answer = await peerB.createAnswer()
  await peerB.setLocalDescription(answer)


  await peerA.setLocalDescription(offer)
  await peerA.setRemoteDescription(answer)


  // 添加 candidate
  peerA.onicecandidate = event => {
    if (event.candidate) {
      peerB.addIceCandidate(event.candidate)
    }
  }


  // 检测连接状态
  peerA.onconnectionstatechange = () => {
    if (peerA.connectionState === 'connected') {
      console.log('对等连接成功！')
    }
  }

  
}




onMounted(() => {

  init()
  

})



</script>

<template>
  <div class="chat">
    <div class="client left">
      <h1>chatA</h1>
      <video ref="videoA" autoplay></video>
      <button @click="">连接</button>
    </div>
    <div class="client right">
      <h1>chatB</h1>
      <video ref="videoB" autoplay></video>
    </div>
  </div>
</template>

<style scoped>
.chat{
  display: flex;
  background-color: rgba(128, 128, 128, 0.274);
}
.client{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.client button{
  width: max-content;
}
</style>
